package LeetCode;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;

public class LC_352_DataStreamasDisjointIntervals {

    public static void main(String[] args) {

    }

    public class Interval {
        int start;
        int end;

        Interval() {
            start = 0;
            end = 0;
        }

        Interval(int s, int e) {
            start = s;
            end = e;
        }
    }

    public class SummaryRanges {
        TreeSet<Interval> set;

        public SummaryRanges() {
            set = new TreeSet<>(Comparator.comparingInt(a -> a.start));
        }

        public void addNum(int val) {
            Interval t = new Interval(val, val);
            Interval floor = set.floor(t);
            if (floor != null) {
                if (val <= floor.end) {
                    return;
                } else if (val == floor.end + 1) {
                    t.start = floor.start;
                    set.remove(floor);
                }
            }
            Interval ceil = set.higher(t);
            if (ceil != null) {
                if (ceil.start == val + 1) {
                    t.end = ceil.end;
                    set.remove(ceil);
                }
            }
            set.add(t);
        }

        public List<Interval> getIntervals() {
            return Arrays.asList(set.toArray(new Interval[0]));
        }
    }

}